package com.ifsaid.im.context;

import com.ifsaid.im.service.IEasemobImService;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;

/**
 * @description: 环信 返回给我们的 token
 * @author: Wang Chen Chen<932560435@qq.com>
 * @date: 2019/11/4 15:13
 */

@Getter
@ToString
@Slf4j
@Component
public class EasemobImToken {

    /**
     * @description: 当前 App 的 UUID 值
     * @date: 2019/11/4 15:15
     */
    private String application;

    /**
     * @description: 有效的token字符串
     * @date: 2019/11/4 15:15
     */
    private String accessToken;

    /**
     * @description: token 有效时间，以秒为单位，在有效期内不需要重复获取
     * @date: 2019/11/4 15:15
     */
    private Long expiresIn;

    public void setValue(String application, String accessToken, Integer expiresIn) {
        this.application = application;
        this.accessToken = accessToken;
        long currentTimeSecond = LocalDateTime.now().toEpochSecond(OffsetDateTime.now().getOffset());
        // 设置过期时间，当前时间加上过期秒数
        this.expiresIn = (currentTimeSecond + expiresIn);
    }

    @Autowired
    private IEasemobImService easemobImService;

    /**
     * @description: 判断 token 是否过期 true: 过期了， false：没有过期
     * @author: Wang Chen Chen<932560435@qq.com>
     * @date: 2019/11/4 15:16
     */
    public void isExpired() {
        if (StringUtils.isEmpty(accessToken)
                || StringUtils.isEmpty(application)
                || expiresIn == null
                || expiresIn > 1) {
            easemobImService.refreshToken();
        }
        // 获取当前时间秒
        long currentTimeSecond = LocalDateTime.now().toEpochSecond(OffsetDateTime.now().getOffset());
        if (currentTimeSecond > expiresIn) {
            easemobImService.refreshToken();
        }
    }

}
